/*
 * Copyright (C) 2008 Alessandro Sivieri <alessandro.sivieri@chimera-bellerofonte.eu>.
 *
 *  This file is part of Daex.
 *
 *  Daex is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Foobar is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */
package eu.chimera_bellerofonte.tesi.ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.logging.Level;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.BevelBorder;
import javax.swing.text.JTextComponent;

import eu.chimera_bellerofonte.tesi.DaexIcon;
import eu.chimera_bellerofonte.tesi.DaexLogger;


/**
 * <p>Classe di descrizione del dialogo che visualizza l'output da console.</p>
 * <p>E' creata come Singleton per sottolineare il fatto che essa sia
 * costituita da un'unica istanza.</p>
 * 
 * @author Sivieri Alessandro
 * @author Vitucci Nicola
 * @version 14/mag/07
 */
public class ConsoleDialog extends JPanel
{

	private static final long serialVersionUID = 1L;
	private static ConsoleDialog consoleDialog=null;
	private JScrollPane jScrollPane = null;
	private JTextPane jTextPane = null;
	private JPanel jPanel = null;
	private JButton printButton = null;
	private JButton saveButton = null;

	/**
	 * This is the default constructor
	 */
	private ConsoleDialog()
	{
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize()
	{
		this.setSize(589, 322);
		this.setLayout(new BorderLayout());
		this.add(getJScrollPane(), BorderLayout.CENTER);
		this.add(getJPanel(), BorderLayout.SOUTH);
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane()
	{
		if (jScrollPane == null)
		{
			jScrollPane = new JScrollPane();
			jScrollPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
			jScrollPane.setViewportView(getJTextPane());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTextPane	
	 * 	
	 * @return javax.swing.JTextPane	
	 */
	private JTextPane getJTextPane()
	{
		if (jTextPane == null)
		{
			jTextPane = new JTextPane();
			jTextPane.setEditable(false);
		}
		return jTextPane;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel()
	{
		if (jPanel == null)
		{
			jPanel = new JPanel();
			jPanel.setLayout(new FlowLayout());
			jPanel.add(getPrintButton(), null);
			jPanel.add(getSaveButton(), null);
		}
		return jPanel;
	}

	/**
	 * This method initializes printButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getPrintButton()
	{
		if (printButton == null)
		{
			printButton = new JButton();
			printButton.setMnemonic(KeyEvent.VK_S);
			printButton.setToolTipText("Stampa cio' che e' in questo momento visualizzato nella console");
			printButton.setText("Stampa la cache");
			printButton.setIcon(new ImageIcon(getClass().getResource(DaexIcon.PRINT)));
			printButton.addActionListener(new java.awt.event.ActionListener()
			{
				public void actionPerformed(java.awt.event.ActionEvent e)
				{
					try
					{
						if(getJTextPane().getText().length()>0)
						{
							Doc doc=new SimpleDoc(getJTextPane().getText(), DocFlavor.STRING.TEXT_PLAIN, null);
							PrintService[] services=PrintServiceLookup.lookupPrintServices(DocFlavor.STRING.TEXT_PLAIN, null);
							if(services.length > 0)
							{
								DocPrintJob job = services[0].createPrintJob();
						        job.print(doc, null);
						        DaexLogger.getDaexLogger().info("Stampa correttamente effettuata");
							}
						}
						else
						{
							JOptionPane.showMessageDialog(ConsoleDialog.this, "Non hai output nella console!", "Stampa inutile", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(DaexIcon.INFO)));
						}
					}
					catch (PrintException e1)
					{
						DaexLogger.getDaexLogger().log(Level.WARNING, "Impossibile stampare", e1);
						JOptionPane.showMessageDialog(ConsoleDialog.this, "Impossibile stampare!", "Errore di stampa", JOptionPane.ERROR_MESSAGE, new ImageIcon(getClass().getResource(DaexIcon.ERROR)));
					}
				}
			});
		}
		return printButton;
	}
	
	/**
	 * Metodo Singleton per ottenere l'unica istanza del dialogo
	 * che visualizza l'output dei processi.
	 * 
	 * @return l'istanza del dialogo dei processi
	 */
	public static ConsoleDialog getConsole()
	{
		if(consoleDialog==null)
		{
			consoleDialog=new ConsoleDialog();
		}
		// meglio anche qui
		consoleDialog.jTextPane.setCaretPosition(consoleDialog.jTextPane.getDocument().getLength());
		return consoleDialog;
	}
	
	/**
	 * This method initializes saveButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getSaveButton()
	{
		if (saveButton == null)
		{
			saveButton = new JButton();
			saveButton.setMnemonic(KeyEvent.VK_S);
			saveButton.setToolTipText("Salva la cache su file");
			saveButton.setText("Salva su file");
			saveButton.setIcon(new ImageIcon(getClass().getResource(DaexIcon.SAVEFILEAS)));
			saveButton.addActionListener(new java.awt.event.ActionListener()
			{
				public void actionPerformed(java.awt.event.ActionEvent e)
				{
					if(getJTextPane().getText().length()>0)
					{
						String result=FileChooserUtility.saveFile(ConsoleDialog.this, System.getProperty("user.home"), "output.txt", "Salvataggio output", ".txt");
						if(result!=null)
						{
							try
							{
								FileOutputStream out=new FileOutputStream(result);
								OutputStreamWriter out_w=new OutputStreamWriter(out);
								getJTextPane().write(out_w);
								out_w.flush();
								out_w.close();
								out.flush();
								out.close();
							}
							catch (IOException e1)
							{
								DaexLogger.getDaexLogger().log(Level.WARNING, "Impossibile salvare sul file "+result, e1);
							}
						}
					}
					else
					{
						JOptionPane.showMessageDialog(ConsoleDialog.this, "Non hai output nella console!", "Stampa inutile", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(DaexIcon.INFO)));
					}
				}
			});
		}
		return saveButton;
	}
	
	/**
	 * Metodo per ottenere l'istanza della console per visualizzare
	 * il testo in output.
	 * 
	 * @see javax.swing.text.JTextComponent#setText(String)
	 * @return un componente avente il metodo setText()
	 */
	public JTextComponent getDocument()
	{
		return getJTextPane();
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"

